package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/tdengine"
	"database/sql"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/xuri/excelize/v2"
	"paco_toolkit/DMXFGW"
)

var Feed_record = feed_record{}

type feed_record struct {
}

func (a *feed_record) Get_bak(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	order := r.GetString("order")

	sn := gconv.String(params["sn"])
	addr := gconv.String(params["addr"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])

	hnum := gconv.String(params["hnum"])
	hnum_prefix := gconv.String(params["hnum_prefix"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])

	tb_record := gconv.String(params["tb_record"])
	feed_type := gconv.String(params["feed_type"])
	begin_end := gconv.String(params["begin_end"])

	where := " rectime>'2022-01-01' and rectime<='2050-01-01' and mode>=0 "

	if addr != "" {
		where += " and addr='" + addr + "'"
	}
	if sn != "" {
		where += " and sn = '" + sn + "' "
	}
	if hnum != "" {
		where += " and hnum = '" + hnum + "' "
	}
	if hnum_prefix != "" {
		where += " and hnum LIKE '" + hnum_prefix + "%' "
	}
	if tb_record != "" {
		if gconv.Int(tb_record) == 0 {
			where += " and IFNULL(tb_record,0)=0  "
		} else {
			where += " and tb_record='" + tb_record + "'"
		}
	}
	if feed_type != "" {
		where += " and feed_type='" + feed_type + "'"
	}
	if begin_end != "" {
		where += " and begin_end='" + begin_end + "'"
	}
	if begin != "" {
		where += fmt.Sprintf(" and DATE(rectime)>='%s' ", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and DATE(rectime)<='%s' ", end)
	}
	if houseid != "" {
		where += fmt.Sprintf(" and addr in (SELECT device_addr AS addr FROM t_device WHERE houseid=%s)   ", houseid)
	}
	if farmid != "" {
		where += fmt.Sprintf(" and addr in (SELECT device_addr AS addr FROM t_device WHERE houseid in (SELECT id as houseid FROM t_house WHERE farmid=%s))   ", farmid)
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
			//where += fmt.Sprintf(" and addr in (SELECT device_addr FROM t_user_device WHERE userid='%s')",userid)
		}

		db := g.DB(g.Cfg().GetString("custom.db_name"))

		model := db.Model("t_feed_record")
		if order != "" {
			model = model.Order(order)
		} else {
			model = model.Order(" hnum asc,rectime desc ")
		}
		records, error := model.Where(where).All()
		if error != nil {
			g.Log().Line().Error(error)
			res["msg"] = error.Error()
			res["code"] = -1
		} else {
			list := records.List()
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_record) Get(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	order := r.GetString("order")

	sn := gconv.String(params["sn"])
	addr := gconv.String(params["addr"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])

	hnum := gconv.String(params["hnum"])
	//hnum_prefix := gconv.String(params["hnum_prefix"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])

	tb_record := gconv.String(params["tb_record"])
	feed_type := gconv.String(params["feed_type"])
	debug := gconv.String(params["debug"])
	begin_end := gconv.String(params["begin_end"])

	fields := gconv.String(params["fields"])

	where := " rectime>'2022-01-01' and rectime<='2050-01-01' and mode>=0 "

	if addr != "" {
		where += " and addr in ('" + addr + "')"
	}
	if sn != "" {
		where += " and sn = '" + sn + "' "
	}
	if hnum != "" {
		where += " and hnum = '" + hnum + "' "
	}
	if tb_record != "" {
		where += " and tb_record = " + tb_record + " "
	}
	if feed_type != "" {
		where += " and feed_type=" + feed_type + ""
	}
	if debug != "" {
		where += " and debug=" + debug + ""
	}
	if begin_end != "" {
		where += " and begin_end=" + begin_end + ""
	}
	if begin != "" {
		where += fmt.Sprintf(" and rectime>='%s' ", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and rectime<='%s' ", end)
	}
	if houseid != "" {
		//获取网关编码
		addrArr := dao.T_device.GetAddrArr("houseid=" + houseid)
		where += fmt.Sprintf(" and addr in ('%s')   ", gstr.Join(addrArr, "','"))
	}
	if farmid != "" {
		addrArr := dao.T_device.GetAddrArr("farmid=" + farmid)
		where += fmt.Sprintf(" and addr in ('%s')   ", gstr.Join(addrArr, "','"))
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
			//where += fmt.Sprintf(" and addr in (SELECT device_addr FROM t_user_device WHERE userid='%s')",userid)
		}

		/*db := g.DB(g.Cfg().GetString("custom.db_name"))

		model := db.Model("t_feed_record")
		if order != "" {
			model = model.Order(order)
		} else {
			model = model.Order(" hnum asc,rectime desc ")
		}
		records, error := model.Where(where).All()
		*/

		orders := ""
		if order != "" {
			orders = order
		} else {
			orders = " hnum asc,rectime desc "
		}
		if fields == "" {
			fields = "*"
		}
		sql := fmt.Sprintf(" SELECT %s FROM `t_hzfgw_record` where %s order by %s", fields, where, orders)
		g.Log().Line(true).Infof(sql)
		list := tdengine.GetRecordsNew(sql)
		res["code"] = 0
		res["data"] = list

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_record) GetPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	sn := gconv.String(params["sn"])
	addr := gconv.String(params["addr"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])

	hnum := gconv.String(params["hnum"])
	//hnum_prefix := gconv.String(params["hnum_prefix"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])

	tb_record := gconv.String(params["tb_record"])
	feed_type := gconv.String(params["feed_type"])
	debug := gconv.String(params["debug"])
	begin_end := gconv.String(params["begin_end"])
	alarm := gconv.String(params["alarm"])
	fields := gconv.String(params["fields"])

	where := " rectime>'2022-01-01' and rectime<='2050-01-01' and mode>=0 "

	if addr != "" {
		where += " and addr='" + addr + "'"
	}
	if sn != "" {
		where += " and sn = '" + sn + "' "
	}
	if hnum != "" {
		where += " and hnum = '" + hnum + "' "
	}
	if tb_record != "" {
		where += " and tb_record = " + tb_record + " "
	}
	if feed_type != "" {
		where += " and feed_type=" + feed_type + ""
	}
	if debug != "" {
		where += " and debug=" + debug + ""
	}

	if alarm == "1" {
		//出水故障
		where += " and err>0 and feed_type=0 and begin_end=0 "
	}
	if begin_end != "" {
		where += " and begin_end=" + begin_end + ""
	}
	if begin != "" {
		where += fmt.Sprintf(" and rectime>='%s' ", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and rectime<='%s' ", end)
	}
	if houseid != "" {
		//获取网关编码
		addrArr := dao.T_device.GetAddrArr("houseid=" + houseid)
		where += fmt.Sprintf(" and addr in ('%s')   ", gstr.Join(addrArr, "','"))
	}
	if farmid != "" {
		addrArr := dao.T_device.GetAddrArr("farmid=" + farmid)
		where += fmt.Sprintf(" and addr in ('%s')   ", gstr.Join(addrArr, "','"))
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
			//where += fmt.Sprintf(" and addr in (SELECT device_addr FROM t_user_device WHERE userid='%s')",userid)
		}

		orders := ""
		if order != "" {
			orders = order
		} else {
			orders = " hnum asc,rectime desc "
		}
		if fields == "" {
			fields = "*"
		}

		var taosDSN = g.Cfg().GetString("taos.connect_str")
		//g.Log().Line(true).Info("DSN:%s", taosDSN)
		taos, err := sql.Open("taosRestful", taosDSN)
		defer taos.Close()
		if err != nil {
			g.Log().Line(true).Errorf("failed to connect TDengine, err:%s", err.Error())
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			rows, err := taos.Query(fmt.Sprintf("SELECT COUNT(*) as num FROM `t_hzfgw_record` where %s", where))
			defer rows.Close()
			if err != nil {
				g.Log().Line(true).Errorf("failed to select from table, err:%s", err.Error())
			} else {

				count := 0
				for rows.Next() {
					var r struct {
						num uint32
					}
					err := rows.Scan(&r.num)
					if err != nil {
						g.Log().Line(true).Error(err)
						break
					}
					count = int(r.num)

				}

				res["count"] = count
				start := limit*page - limit
				if start < 0 {
					start = 0
				}

				sql := fmt.Sprintf("SELECT %s FROM `t_hzfgw_record` where %s  order by %s limit %d,%d", fields, where, orders, start, limit)
				list := tdengine.GetRecordsNew(sql)
				g.Log().Line(true).Infof(sql)
				res["code"] = 0
				res["data"] = list
			}

		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_record) Export(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	order := r.GetString("order")
	sn := gconv.String(params["sn"])
	addr := gconv.String(params["addr"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])

	hnum := gconv.String(params["hnum"])
	//hnum_prefix := gconv.String(params["hnum_prefix"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])

	tb_record := gconv.String(params["tb_record"])
	feed_type := gconv.String(params["feed_type"])
	debug := gconv.String(params["debug"])
	begin_end := gconv.String(params["begin_end"])

	where := " rectime>'2022-01-01' and rectime<='2050-01-01' and mode>=0 "
	if addr != "" {
		where += " and addr='" + addr + "'"
	}
	if sn != "" {
		where += " and sn = '" + sn + "' "
	}
	if hnum != "" {
		where += " and hnum = '" + hnum + "' "
	}
	if tb_record != "" {
		where += " and tb_record = " + tb_record + " "
	}
	if feed_type != "" {
		where += " and feed_type=" + feed_type + ""
	}
	if debug != "" {
		where += " and debug=" + debug + ""
	}
	if begin_end != "" {
		where += " and begin_end=" + begin_end + ""
	}
	if begin != "" {
		where += fmt.Sprintf(" and rectime>='%s' ", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and rectime<='%s' ", end)
	}
	if houseid != "" {
		//获取网关编码
		addrArr := dao.T_device.GetAddrArr("houseid=" + houseid)
		where += fmt.Sprintf(" and addr in ('%s')   ", gstr.Join(addrArr, "','"))
	}
	if farmid != "" {
		addrArr := dao.T_device.GetAddrArr("farmid=" + farmid)
		where += fmt.Sprintf(" and addr in ('%s')   ", gstr.Join(addrArr, "','"))
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
			//where += fmt.Sprintf(" and addr in (SELECT device_addr FROM t_user_device WHERE userid='%s')",userid)
		}

		orders := ""
		if order != "" {
			orders = order
		} else {
			orders = " hnum asc,rectime desc "
		}
		list := tdengine.GetRecords(fmt.Sprintf("SELECT * FROM `t_hzfgw_record` where %s order by %s", where, orders))

		f := excelize.NewFile()
		defer func() {
			if err := f.Close(); err != nil {
				g.Log().Line(true).Error(err)
			}
		}()

		// 创建一个工作表
		index, err := f.NewSheet("Sheet1")
		if err != nil {
			g.Log().Line(true).Error(err)
		}

		//样式
		style, _ := f.NewStyle(&excelize.Style{
			Fill: excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
			Font: &excelize.Font{Color: "#ffffff"},
		})
		//列宽
		f.SetColWidth("Sheet1", "A", "M", 20)
		// 标题
		f.SetCellValue("Sheet1", "A1", "终端编码")
		f.SetCellValue("Sheet1", "B1", "饲喂器SN")
		f.SetCellValue("Sheet1", "C1", "栏位号")
		f.SetCellValue("Sheet1", "D1", "记录时间")
		f.SetCellValue("Sheet1", "E1", "模式")
		f.SetCellValue("Sheet1", "F1", "方式")
		f.SetCellValue("Sheet1", "G1", "类型")
		f.SetCellValue("Sheet1", "H1", "触碰动作")
		//f.SetCellValue("Sheet1", "I1", "描述")
		f.SetCellValue("Sheet1", "I1", "出料水(kg/L)")
		f.SetCellValue("Sheet1", "J1", "累计出料(kg)")
		f.SetCellValue("Sheet1", "K1", "累计出水(L)")
		f.SetCellValue("Sheet1", "L1", "电机电流(mA)")

		f.SetCellStyle("Sheet1", "A1", "A1", style)
		f.SetCellStyle("Sheet1", "B1", "B1", style)
		f.SetCellStyle("Sheet1", "C1", "C1", style)
		f.SetCellStyle("Sheet1", "D1", "D1", style)
		f.SetCellStyle("Sheet1", "E1", "E1", style)
		f.SetCellStyle("Sheet1", "F1", "F1", style)
		f.SetCellStyle("Sheet1", "G1", "G1", style)
		f.SetCellStyle("Sheet1", "H1", "H1", style)
		f.SetCellStyle("Sheet1", "I1", "I1", style)
		f.SetCellStyle("Sheet1", "J1", "J1", style)
		f.SetCellStyle("Sheet1", "K1", "K1", style)
		f.SetCellStyle("Sheet1", "L1", "L1", style)
		//f.SetCellStyle("Sheet1", "M1", "M1", style)
		//行
		if len(list) > 0 {
			count := 0
			for k, v := range list {
				count++
				//行数限制
				if count > 1048000 {
					break
				}
				f.SetCellValue("Sheet1", fmt.Sprintf("A%d", k+2), gconv.String(v.Addr))
				f.SetCellValue("Sheet1", fmt.Sprintf("B%d", k+2), gconv.String(v.Sn))
				f.SetCellValue("Sheet1", fmt.Sprintf("C%d", k+2), gconv.String(v.Hnum))
				f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), gconv.String(v.RectimeFormat))
				//device_type := DMXFGW.MODE

				mode_str := ""
				mode := gconv.Int(v.Mode)
				_sn := gconv.Int(v.Sn)
				if _sn < 20000000 {
					//饲喂器
					if mode == 0 {
						mode_str = "停用"
					} else if mode == DMXFGW.FEED_MODE_PG {
						mode_str = "妊娠"
					} else if mode == DMXFGW.FEED_MODE_LACTATION {
						mode_str = "哺乳"
					} else if mode == DMXFGW.FEED_MODE_NURSE {
						mode_str = "保育"
					} else if mode == DMXFGW.FEED_MODE_FAT {
						mode_str = "育肥"
					} else if mode == DMXFGW.FEED_MODE_TIMER {
						mode_str = "定时"
					}
				}
				if _sn > 20000000 && _sn < 30000000 {
					//粥料器
					if mode == 0 {
						mode_str = "停用"
					} else if mode == DMXFGW.FG_MODE_NURSE {
						mode_str = "保育"
					} else if mode == DMXFGW.FG_MODE_FAT {
						mode_str = "育肥"
					} else if mode == DMXFGW.FG_MODE_TIMER {
						mode_str = "定时"
					}
				}

				f.SetCellValue("Sheet1", fmt.Sprintf("E%d", k+2), mode_str)

				type_str := ""
				tb_record := gconv.Int(v.Tb_record)
				remote := gconv.Int(v.Remote)
				emergency := gconv.Int(v.Emergency)
				auto := gconv.Int(v.Auto)

				if tb_record > 0 {

				} else {
					if auto == 0 {
						type_str = "手动"
					} else if auto == 1 {
						type_str = "自动"
					}

					if remote > 0 {
						type_str += "(远程)"
					}
					if emergency > 0 {
						type_str += "(紧急)"
					}
				}

				f.SetCellValue("Sheet1", fmt.Sprintf("F%d", k+2), type_str)

				feed_type_str := ""
				if tb_record > 0 {

				} else {
					feed_type := gconv.Int(v.Feed_type)
					if feed_type == 0 {
						feed_type_str = "出水"
					} else if feed_type == 1 {
						feed_type_str = "出料"
					}
				}

				f.SetCellValue("Sheet1", fmt.Sprintf("G%d", k+2), feed_type_str)
				tb_record_str := ""
				if tb_record > 0 {
					tb_record_str = "触碰"
				}
				f.SetCellValue("Sheet1", fmt.Sprintf("H%d", k+2), tb_record_str)
				//f.SetCellValue("Sheet1", fmt.Sprintf("I%d", k+2), gconv.String(v["event"]))
				amount_str := ""
				if tb_record > 0 {

				} else {
					amount_str = gconv.String(v.Amount)
				}
				f.SetCellValue("Sheet1", fmt.Sprintf("I%d", k+2), amount_str)
				day_use_feed_str := ""
				if tb_record > 0 {

				} else {
					day_use_feed_str = gconv.String(v.Day_use_feed)
				}
				f.SetCellValue("Sheet1", fmt.Sprintf("J%d", k+2), day_use_feed_str)
				day_use_water_str := ""
				if tb_record > 0 {

				} else {
					day_use_water_str = gconv.String(v.Day_use_water)
				}
				f.SetCellValue("Sheet1", fmt.Sprintf("K%d", k+2), day_use_water_str)
				f.SetCellValue("Sheet1", fmt.Sprintf("L%d", k+2), gconv.Float32(v.Motor_cur))
			}
		}

		// 设置工作簿的默认工作表
		f.SetActiveSheet(index)

		f.Write(r.Response.Writer)

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
		r.Response.WriteJson(res)
	}
	r.ExitAll()
}

func (a *feed_record) ExportSimple(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	order := r.GetString("order")
	sn := gconv.String(params["sn"])
	addr := gconv.String(params["addr"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])

	hnum := gconv.String(params["hnum"])
	//hnum_prefix := gconv.String(params["hnum_prefix"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])

	tb_record := gconv.String(params["tb_record"])
	feed_type := gconv.String(params["feed_type"])
	begin_end := gconv.String(params["begin_end"])

	where := " rectime>'2022-01-01' and rectime<='2050-01-01' and mode>=0 "
	if addr != "" {
		where += " and addr='" + addr + "'"
	}
	if sn != "" {
		where += " and sn = '" + sn + "' "
	}
	if hnum != "" {
		where += " and hnum = '" + hnum + "' "
	}
	if tb_record != "" {
		where += " and tb_record = " + tb_record + " "
	}
	if feed_type != "" {
		where += " and feed_type=" + feed_type + ""
	}
	if begin_end != "" {
		where += " and begin_end=" + begin_end + ""
	}
	if begin != "" {
		where += fmt.Sprintf(" and rectime>='%s' ", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and rectime<='%s' ", end)
	}
	var houseNameArr []string
	var farmNameArr []string
	var deviceAddrArr []string
	if houseid != "" {
		//获取网关编码
		addrArr := dao.T_device.GetAddrArr("houseid=" + houseid)
		farmNameArr, houseNameArr, deviceAddrArr = dao.T_device.GetTopoNameArr("houseid=" + houseid)
		where += fmt.Sprintf(" and addr in ('%s')   ", gstr.Join(addrArr, "','"))

	}
	if farmid != "" {
		addrArr := dao.T_device.GetAddrArr("farmid=" + farmid)
		farmNameArr, houseNameArr, deviceAddrArr = dao.T_device.GetTopoNameArr("houseid=" + houseid)
		where += fmt.Sprintf(" and addr in ('%s')   ", gstr.Join(addrArr, "','"))
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
			//where += fmt.Sprintf(" and addr in (SELECT device_addr FROM t_user_device WHERE userid='%s')",userid)
		}

		orders := ""
		if order != "" {
			orders = order
		} else {
			orders = " hnum asc,rectime desc "
		}
		list := tdengine.GetRecords(fmt.Sprintf("SELECT * FROM `t_hzfgw_record` where %s order by %s", where, orders))

		f := excelize.NewFile()
		defer func() {
			if err := f.Close(); err != nil {
				g.Log().Line(true).Error(err)
			}
		}()

		// 创建一个工作表
		index, err := f.NewSheet("Sheet1")
		if err != nil {
			g.Log().Line(true).Error(err)
		}

		//样式
		style, _ := f.NewStyle(&excelize.Style{
			Fill: excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
			Font: &excelize.Font{Color: "#ffffff"},
		})
		style_yellow_font, _ := f.NewStyle(&excelize.Style{
			Font: &excelize.Font{Color: "#FF8010"},
		})
		style_blue_font, _ := f.NewStyle(&excelize.Style{
			Font: &excelize.Font{Color: "#4958b9"},
		})
		style_green_font, _ := f.NewStyle(&excelize.Style{
			Font: &excelize.Font{Color: "#05982E"},
		})
		//列宽
		f.SetColWidth("Sheet1", "A", "J", 20)
		// 标题
		f.SetCellValue("Sheet1", "A1", "养殖场")
		f.SetCellValue("Sheet1", "B1", "栏舍单元")
		f.SetCellValue("Sheet1", "C1", "终端编码")
		f.SetCellValue("Sheet1", "D1", "饲喂器SN")
		f.SetCellValue("Sheet1", "E1", "栏位号")
		f.SetCellValue("Sheet1", "F1", "记录时间")
		f.SetCellValue("Sheet1", "G1", "模式")
		f.SetCellValue("Sheet1", "H1", "方式")
		f.SetCellValue("Sheet1", "I1", "类型")
		f.SetCellValue("Sheet1", "J1", "出料水(kg/L)")

		f.SetCellStyle("Sheet1", "A1", "A1", style)
		f.SetCellStyle("Sheet1", "B1", "B1", style)
		f.SetCellStyle("Sheet1", "C1", "C1", style)
		f.SetCellStyle("Sheet1", "D1", "D1", style)
		f.SetCellStyle("Sheet1", "E1", "E1", style)
		f.SetCellStyle("Sheet1", "F1", "F1", style)
		f.SetCellStyle("Sheet1", "G1", "G1", style)
		f.SetCellStyle("Sheet1", "H1", "H1", style)
		f.SetCellStyle("Sheet1", "I1", "I1", style)
		f.SetCellStyle("Sheet1", "J1", "J1", style)
		//f.SetCellStyle("Sheet1", "M1", "M1", style)
		//行
		if len(list) > 0 {
			count := 0
			for k, v := range list {
				count++
				//行数限制
				if count > 1048000 {
					break
				}

				var farmname string
				var housename string
				for i := 0; i < len(deviceAddrArr); i++ {
					if deviceAddrArr[i] == v.Addr {
						farmname = farmNameArr[i]
						housename = houseNameArr[i]
					}
				}
				f.SetCellValue("Sheet1", fmt.Sprintf("A%d", k+2), gconv.String(farmname))
				f.SetCellValue("Sheet1", fmt.Sprintf("B%d", k+2), gconv.String(housename))
				f.SetCellValue("Sheet1", fmt.Sprintf("C%d", k+2), gconv.String(v.Addr))
				f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), gconv.String(v.Sn))
				f.SetCellValue("Sheet1", fmt.Sprintf("E%d", k+2), gconv.String(v.Hnum))

				f.SetCellValue("Sheet1", fmt.Sprintf("F%d", k+2), gconv.String(v.RectimeFormat))
				mode_str := ""
				mode := gconv.Int(v.Mode)
				_sn := gconv.Int(v.Sn)
				if _sn < 20000000 {
					//饲喂器
					if mode == 0 {
						mode_str = "停用"
					} else if mode == DMXFGW.FEED_MODE_PG {
						mode_str = "妊娠"
					} else if mode == DMXFGW.FEED_MODE_LACTATION {
						mode_str = "哺乳"
					} else if mode == DMXFGW.FEED_MODE_NURSE {
						mode_str = "保育"
					} else if mode == DMXFGW.FEED_MODE_FAT {
						mode_str = "育肥"
					} else if mode == DMXFGW.FEED_MODE_TIMER {
						mode_str = "定时"
					}
				}
				if _sn > 20000000 && _sn < 30000000 {
					//粥料器
					if mode == 0 {
						mode_str = "停用"
					} else if mode == DMXFGW.FG_MODE_NURSE {
						mode_str = "保育"
					} else if mode == DMXFGW.FG_MODE_FAT {
						mode_str = "育肥"
					} else if mode == DMXFGW.FG_MODE_TIMER {
						mode_str = "定时"
					}
				}

				f.SetCellValue("Sheet1", fmt.Sprintf("G%d", k+2), mode_str)

				type_str := ""
				remote := gconv.Int(v.Remote)
				emergency := gconv.Int(v.Emergency)
				auto := gconv.Int(v.Auto)

				if auto == 0 {
					type_str = "手动"
					f.SetCellStyle("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("H%d", k+2), style_yellow_font)
				} else if auto == 1 {
					type_str = "自动"
					f.SetCellStyle("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("H%d", k+2), style_green_font)
				}

				if remote > 0 {
					type_str += "(远程)"
				}
				if emergency > 0 {
					type_str += "(紧急)"
				}

				f.SetCellValue("Sheet1", fmt.Sprintf("H%d", k+2), type_str)

				feed_type_str := ""
				feed_type := gconv.Int(v.Feed_type)
				if feed_type == 0 {
					feed_type_str = "出水"
					f.SetCellStyle("Sheet1", fmt.Sprintf("I%d", k+2), fmt.Sprintf("I%d", k+2), style_blue_font)
				} else if feed_type == 1 {
					feed_type_str = "出料"
					f.SetCellStyle("Sheet1", fmt.Sprintf("I%d", k+2), fmt.Sprintf("I%d", k+2), style_yellow_font)
				}

				f.SetCellValue("Sheet1", fmt.Sprintf("I%d", k+2), feed_type_str)

				amount_str := gconv.String(v.Amount)
				f.SetCellValue("Sheet1", fmt.Sprintf("J%d", k+2), amount_str)

			}
		}

		// 设置工作簿的默认工作表
		f.SetActiveSheet(index)

		f.Write(r.Response.Writer)

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
		r.Response.WriteJson(res)
	}
	r.ExitAll()
}
